import { Message, Modal } from '@arco-design/web-vue';
import { defineStore } from 'pinia';
import { reactive, ref, toRefs } from 'vue';
import router from '../../../router';
import { changeData, delData, savetData } from './api';
export const useGoodsStore = defineStore(
  'goods',
  () => {
    const model = () => ({
      title: ``,
      img: ``,
      price: 0,
      original_price: 0,
      stock: 0,
      imgs: ``,
      shipping_address: ``,
      goods_type_id: [],
      sold: 0,
      type: 0,
      // norm: [
      //   { name: '颜色', value: ['白色', '黑色', '卡其色'] },
      //   { name: '尺码', value: ['39', '40', '41'] },
      // ],
      norm: [],
      norm_arr: [],
      status: 1,
      courier_fee: 0,
      params: ``,
      content: ``,
      sort: 0,
      recommend: [],
      synopsis: ``,
      keyword: ``,
      unit: ``,
      video: ``,
      isAddVideo: 0,
    });
    const state = reactive({
      back() {
        router.back();
        state.stepIndex = '基础信息';
        state.form = model();
      },
      formRef: ref(),
      rules: {
        goods_type_id: [
          { required: true, message: '请选择商品分类', group: '基础信息' },
        ],
        title: [
          { required: true, message: '请输入商品名称', group: '基础信息' },
        ],
        synopsis: [
          { required: true, message: '请输入商品简介', group: '基础信息' },
        ],
        unit: [{ required: true, message: '请输入单位', group: '基础信息' }],
        imgs: [{ required: true, message: '请上传轮播图', group: '基础信息' }],
        status: [{ required: true, message: '请选择状态', group: '基础信息' }],
        type: [{ required: true, message: '请选择规格', group: '规格库存' }],
        img: [{ required: true, message: '请上传商品图片', group: '规格库存' }],
        price: [{ required: true, message: '请输入售价', group: '规格库存' }],
        original_price: [
          { required: true, message: '请输入原价', group: '规格库存' },
        ],
        stock: [{ required: true, message: '请输入库存', group: '规格库存' }],
        shipping_address: [
          { required: true, message: '请输入发货地址', group: '物流设置' },
        ],
        courier_fee: [
          { required: true, message: '请输入运费', group: '物流设置' },
        ],
        sort: [{ required: true, message: '请输入排序', group: '营销设置' }],
        sold: [
          { required: true, message: '请输入已售数量', group: '营销设置' },
        ],
      },
      typeOptions: [],
      recommendOptions: [
        { label: '热销商品', value: 1 },
        { label: '为您推荐', value: 2 },
        { label: '猜你喜欢', value: 3 },
      ],
      step: `基础信息,规格库存,商品详情,产品参数,物流设置,营销设置`,
      stepIndex: `基础信息`,
      rowSelection: {
        showCheckedAll: true,
        type: 'checkbox',
      },
      selectedKeys: [],
      form: model(),
      async save({ errors }) {
        // console.log(state.form.norm);

        console.log(state.form);
        for (const rule in errors) {
          Message.warning(errors[rule].message);
          state.stepIndex = state.formRef.rules[rule][0].group;
          console.log(state.stepIndex);
          break;
        }
        const vaild = !errors;
        console.log(state.form);
        const form = state.form;
        if (vaild) {
          console.error(form);
          await savetData({
            ...form,
            goods_type_id: form.goods_type_id.join(','),
            recommend: form.recommend.join(','),
            norm: JSON.stringify(form.norm),
            norm_arr: JSON.stringify(form.norm_arr),
          });
          Message.success(form?.id ? '编辑成功' : '新建成功');
          state.stepIndex = `基础信息`;
          // router.replace('/goods/index');
          router.back();
        }
      },
      tableStep: '商品,回收站',
      tableStepIndex: '回收站',
      add() {
        state.form = model();
        router.push({ name: 'goodsadd' });
      },
      async switch(record, fetchData) {
        console.log(record);
        if (!record.id) {
          Message.warning('请选择要操作的商品');
          return;
        }
        await changeData({
          ids: record.id,
          status: record.status,
        });
        Message.success('操作成功');
        fetchData();
      },
      async dels(fetchData) {
        const ids = state.selectedKeys.join(',');
        console.log(ids);
        if (!ids) {
          Message.warning('请选择要删除的商品');
          return;
        }
        Modal.error({
          title: '操作提示',
          content: '是否确认删除所选商品?',
          async onOk() {
            await state.del(ids, fetchData);
          },
        });
      },
      async del(id, fetchData) {
        await delData(id);
        Message.success('删除成功');
        fetchData();
      },
      edit(record) {
        Object.assign(state.form, {
          ...record,
          price: parseFloat(state.form.price),
          original_price: parseFloat(state.form.original_price),
          courier_fee: parseFloat(state.form.courier_fee),
          isAddVideo: !!record.video ? 1 : 0,
        });
        console.log(state.form);
        router.push({ name: 'goodsadd' });
      },
    });
    return {
      ...toRefs(state),
    };
  },
  {
    persist: {
      storage: sessionStorage,
      paths: ['typeOptions', 'form'],
    },
  }
);

export default useGoodsStore;
